package org.hdax.dm.service.impl;

import org.hda.dm.utils.DateUtil;
import org.hda.dm.utils.exception.DmException;
import org.hdax.dm.client.UserClient;
import org.hdax.dm.entity.BaseEntity;
import org.hdax.dm.entity.user.User;
import org.hdax.dm.request.VoVcodeRequest;
import org.hdax.dm.service.UserService;
import org.hdax.dm.vo.CommonResponse;
import org.hdax.dm.vo.entity.user.QueryUserInfoByToken;
import org.hdax.dm.vo.entity.user.Token;
import org.hdax.dm.vo.entity.user.UserVo;
import org.hdax.dm.vo.VoUtil;
import org.hdax.dm.vo.entity.user.VoTokens;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 手机验证正则表达式
     */
    public final String REGEX = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";


    @Override
    public CommonResponse<List<Object>> login(String phone, String password) {
        User user = userClient.findByPhone(phone);
        if (user == null) {
            return VoUtil.returnFail("1006", new DmException("用户名不存在"));
        } else {
            if (!user.getPassword().equals(password)) {
                return VoUtil.returnFail("1006", new DmException("密码错误"));
            }
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        userVo.setUserId(user.getId());
        userVo.setCreatedTime(DateUtil.dateToString(user.getCreatedTime()));
        userVo.setUpdatedTime(DateUtil.dateToString(user.getUpdatedTime()));
        userVo.setBirthday(DateUtil.dateToString(user.getBirthday()));
        List<Object> list = new ArrayList<Object>();
        list.add(userVo);
        list.add(new Token("token:" + userVo.getPhone(), 10, new Date().getTime()));
        return VoUtil.returnSuccess(list);
    }

    @Override
    public CommonResponse getCode(String mobile) {
        if (mobile.matches(REGEX) == false) {
            return VoUtil.returnFail("1001", new DmException("手机号格式不正确"));
        }
        User user = userClient.findByPhone(mobile);
        if (user != null) {
            String item = stringRedisTemplate.opsForValue().get("smscode_" + mobile);
            if (item != null) {
                return VoUtil.returnFail("1002", new DmException("同一手机号60秒内只能发送一次验证码"));
            }
            int minCode = 100000;
            int maxCode = 999999;
            Random random = new Random();
            int code = random.nextInt(maxCode);
            if (code < minCode) {
                code += minCode;
            }
            //向缓存存储 smscode_手机号,验证码
            stringRedisTemplate.opsForValue().set("smscode_" + mobile, code + "", 1, TimeUnit.MINUTES);
            Map<String, Object> msg = new HashMap<String, Object>();
            msg.put("mobile", mobile);
            msg.put("code", code + "");
            //向消息中间件存储要发送的
            rabbitTemplate.convertAndSend("dmsms", msg);
            return VoUtil.returnSuccess("");
        }
        return VoUtil.returnFail("1007", new DmException("手机号未注册"));
    }

    @Override
    public CommonResponse<VoTokens> codeLogin(VoVcodeRequest voVcodeRequest) {
        if (voVcodeRequest.getPhone().matches(REGEX) == false) {
            return VoUtil.returnFail("1001", new DmException("手机号格式不正确"));
        }
        User user = userClient.findByPhone(voVcodeRequest.getPhone());
        if (user != null) {
            String item = stringRedisTemplate.opsForValue().get("smscode_" + voVcodeRequest.getPhone());
            if (item == null) {
                return VoUtil.returnFail("1008", new DmException("请获取验证码"));
            } else if (!voVcodeRequest.getVcode().equals(item)) {
                return VoUtil.returnFail("1008", new DmException("验证码不正确，登录失败"));
            }
            VoTokens voTokens = new VoTokens();
            voTokens.setGenTime(new Date().getTime());
            BeanUtils.copyProperties(user, voTokens);
            voTokens.setExpTime(10);
            stringRedisTemplate.delete("smscode_" + user.getPhone());
            return VoUtil.returnSuccess(voTokens);
        }
        return VoUtil.returnFail("1007", new DmException("手机号未注册"));
    }

    @Override
    public CommonResponse enrollGetCode(String mobile) {
        if (mobile.matches(REGEX) == false) {
            return VoUtil.returnFail("1001", new DmException("手机号格式不正确"));
        }
        User user = userClient.findByPhone(mobile);
        if (user == null) {
            String item = stringRedisTemplate.opsForValue().get("enrollCode_" + mobile);
            if (item != null) {
                return VoUtil.returnFail("1002", new DmException("同一手机号60秒内只能发送一次验证码"));
            }
            int minCode = 100000;
            int maxCode = 999999;
            Random random = new Random();
            int code = random.nextInt(maxCode);
            if (code < minCode) {
                code += minCode;
            }
            //向缓存存储 smscode_手机号,验证码
            stringRedisTemplate.opsForValue().set("enrollCode_" + mobile, code + "", 1, TimeUnit.MINUTES);
            Map<String, Object> msg = new HashMap<String, Object>();
            msg.put("mobile", mobile);
            msg.put("mobile", mobile);
            msg.put("code", code + "");
            //向消息中间件存储要发送的
            rabbitTemplate.convertAndSend("dmsms", msg);
            return VoUtil.returnSuccess("");
        }
        return VoUtil.returnFail("1003", new DmException("手机号已注册"));
    }

    @Override
    public CommonResponse<VoTokens> enrollLogin(VoVcodeRequest voVcodeRequest) {
        if (voVcodeRequest.getPhone().matches(REGEX) == false) {
            return VoUtil.returnFail("1001", new DmException("手机号格式不正确"));
        }
        User user = userClient.findByPhone(voVcodeRequest.getPhone());
        if (user == null) {
            String item = stringRedisTemplate.opsForValue().get("enrollCode_" + voVcodeRequest.getPhone());
            if (item == null) {
                return VoUtil.returnFail("1008", new DmException("请获取验证码"));
            } else if (!voVcodeRequest.getVcode().equals(item)) {
                return VoUtil.returnFail("1008", new DmException("验证码不正确，注册失败"));
            }
            user = new User();
            user.setPhone(voVcodeRequest.getPhone());
            user.setPassword(voVcodeRequest.getPassword());
            user.setSex(0);
            userClient.InsertUser(user);
            stringRedisTemplate.delete("enrollCode_" + user.getPhone());
            return VoUtil.returnSuccess(0);
        }
        return VoUtil.returnFail("1007", new DmException("手机号已注册"));
    }

    @Override
    public CommonResponse<QueryUserInfoByToken> queryUserInfoByToken() {
        return null;
    }

    @Override
    public CommonResponse modifyUserInfo(QueryUserInfoByToken queryUserInfoByToken) {
        User user=new User();
        BeanUtils.copyProperties(queryUserInfoByToken,user);
        userClient.modifyUserInfo(user);
        return VoUtil.returnSuccess(null);
    }
}
